package com.hfzy.ihk.web.aliyuncall.support.cloudcall.handler;


import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.web.aliyuncall.biz.PushDataToBLBiz;
import com.hfzy.ihk.web.aliyuncall.biz.PushDataToEsBiz;
import com.hfzy.ihk.web.aliyuncall.constant.RedisFields;
import com.hfzy.ihk.web.aliyuncall.constant.RedisKey;
import com.hfzy.ihk.web.aliyuncall.constant.RedisTimeOut;
import com.hfzy.ihk.web.aliyuncall.support.cloudcall.base.AbstractCallOutHandler;
import com.hfzy.ihk.web.aliyuncall.support.cloudcall.base.AbstractRecordFileHandler;
import com.hfzy.ihk.web.aliyuncall.support.cloudcall.event.AliyunRecordFileEvent;
import com.hfzy.ihk.web.aliyuncall.support.cloudcall.event.CallHistoryEvent;
import com.hfzy.ihk.web.aliyuncall.vo.AliyunRecordFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by YANFA on 2018/7/31.
 */
@Component
@Scope("prototype")
public class AliyunRecordFileHandler extends AbstractRecordFileHandler<AliyunRecordFile,AliyunRecordFileEvent> {

    Logger logger = LoggerFactory.getLogger(AliyunRecordFileHandler.class);


    @Autowired
    RedisTemplate redisTemplate;

    @Resource
    TaskExecutor pushDataToEsTaskExecutor;


    @Autowired
    PushDataToEsBiz pushDataToEsBiz;

    @Autowired
    PushDataToBLBiz pushDataToBLBiz;

    @Override
    protected String getRecordFileUrl(AliyunRecordFile data) {
        try {
            String url = data.getRecord_file();

            if (StringTools.isEmpty(url))
                return null;
            //解码
            url = new String(url.getBytes("GBK"), "UTF-8");
            logger.info("get url :{}", url);
            return url ;
        }catch (Exception e){
            logger.error("aliyun 解码录音失败 ：{}",data.getRecord_file(),e);
            return null;
        }


    }

    @Override
    protected void dealData(AliyunRecordFile data, String recordFileUrl) {
        //判断redis是否还存在该ressionId 的数据，如果存在先保存到redis 再推Es 因为可能存在呼叫记录还没推到ES 的情况，但是因为ES 的特性所以可以直接将录音推过去先
        Map<String,String> callHistoryMap = null;
        try {

            Boolean bl = redisTemplate.hasKey(RedisKey.CALL_HISTORY_RPIX + data.getOut_id());
            if (bl) {

                callHistoryMap = redisTemplate.opsForHash().entries(RedisKey.CALL_HISTORY_RPIX + data.getOut_id());
                redisTemplate.opsForHash().put(RedisKey.CALL_HISTORY_RPIX + data.getOut_id(), RedisFields.CALL_HISTORY_RECORD_FILE_URL, recordFileUrl);
            }
            //设置到一个set去，用来晚上下载录音job用，这样就不用去查es了
            redisTemplate.opsForSet().add(RedisKey.ALIYUN_RECORD_URL_SET,data.getOut_id()+":"+recordFileUrl);
        }catch (Exception e){
            logger.error("将录音文件写入redis 失败,sessionId:{},recordFileUrl:{}",data.getOut_id(),recordFileUrl,e);
        }

        //判断需不需要推送到保利爱家
        if(callHistoryMap==null){
            pushDataToBLBiz.setReids("url",data.getOut_id());
        }else{//判断是不是保利爱家的URl
            String commmit = callHistoryMap.get(RedisFields.CALL_HISTORY_COMMIT_TO);
            if(StringTools.isNotempty(commmit)&&"11".equals(commmit)){
                try{
                    pushDataToBLBiz.callPushRecordUrl(data.getOut_id(),recordFileUrl);
                }catch (Exception e){
                    pushDataToBLBiz.setReids("url",data.getOut_id());
                }
            }
        }

        //将录音推送到Es
        try {
            Map<String,String> map = new HashMap<>();
            map.put(RedisFields.CALL_HISTORY_SESSION_ID,data.getOut_id());
            map.put(RedisFields.CALL_HISTORY_RECORD_FILE_URL,recordFileUrl);
            String jsonStr = JSONObject.toJSONString(map);
            pushDataToEsTaskExecutor.execute(() -> {
                pushDataToEsBiz.pushRecordFileToEs(data.getOut_id(), recordFileUrl,jsonStr);
            });
        }catch (Exception e){
            try {
                redisTemplate.opsForSet().add(RedisKey.PUSH_RECORD_URL_TO_ES_FAILED, data.getOut_id() + "::" + recordFileUrl);
            }catch (Exception e1){
                e1.printStackTrace();
            }
            logger.error("====>推送url->Es 的线程池爆了",e);
        }

    }
}
